package com.wiloon.java8x.thread.lock.synchronizedx;

import java.util.concurrent.TimeUnit;

/**
 * Created by wiloon on 6/24/17;
 */
public class TestSynchonized {
    public static void main(String[] args) {
        new TestSynchonized().test();
    }

    public void test() {

        new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (Foo.class) {
                    for (; ; ) {
                        System.out.println(Thread.currentThread().getName());
                        try {
                            TimeUnit.SECONDS.sleep(1);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }).start();
        Foo foo = new Foo();

        new Thread(new Task(foo)).start();
        new Thread(new InstanceLock(foo)).start();

    }

    class Foo {

    }

    class Task implements Runnable {
        Foo foo;

        public Task(Foo foo) {
            this.foo = foo;
        }

        @Override
        public void run() {
            synchronized (foo.getClass()) {
                for (; ; ) {
                    System.out.println(Thread.currentThread().getName());
                    try {
                        TimeUnit.SECONDS.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    class InstanceLock implements Runnable {
        Foo foo;

        public InstanceLock(Foo foo) {
            this.foo = foo;
        }

        @Override
        public void run() {
            synchronized (foo) {
                for (; ; ) {
                    System.out.println(Thread.currentThread().getName());
                    try {
                        TimeUnit.SECONDS.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

}
